package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.ResultBean;
import com.jsbj.enums.ConfigDictTypeEnum;
import com.jsbj.tools.BeanUtils;
import com.jsbj.tools.DateUtils;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.SysPermissionAll;
import com.jsbj.user.entities.SysTenantPermission;
import com.jsbj.user.mapper.SysPermissionAllMapper;
import com.jsbj.user.service.ISysDictDataService;
import com.jsbj.user.service.ISysPermissionAllService;
import com.jsbj.user.service.ISysTenantPermissionService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统菜单-页面-按钮表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysPermissionAllServiceImpl extends ServiceImpl<SysPermissionAllMapper, SysPermissionAll> implements ISysPermissionAllService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysTenantPermissionService sysTenantPermissionService;

    @Override
    public List<SysPermissionAll> selectBySysCode(String systemCode) {
        LambdaQueryWrapper<SysPermissionAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermissionAll::getDisabled, 0);
        queryWrapper.eq(SysPermissionAll::getSystemCode, systemCode);
        queryWrapper.orderByAsc(SysPermissionAll::getSort);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<SysPermissionAll> getListData(String inParam) {
        JSONObject object = JSONObject.parseObject(inParam);
        String systemCode = object.getString("systemCode");
        String permissionName = object.getString("permissionName");
        String permissionTypeValue = object.getString("permissionTypeValue");

        LambdaQueryWrapper<SysPermissionAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermissionAll::getDisabled, 0);
        queryWrapper.eq(SysPermissionAll::getSystemCode, systemCode);
        if (StringUtils.isNotEmpty(permissionName)) {
            queryWrapper.like(SysPermissionAll::getPermissionName, permissionName);
        }
        if (StringUtils.isNotEmpty(permissionTypeValue)) {
            queryWrapper.eq(SysPermissionAll::getPermissionTypeValue, permissionTypeValue);
        }
        queryWrapper.orderByAsc(SysPermissionAll::getSort);
        List<SysPermissionAll> tempAll = baseMapper.selectList(queryWrapper);
        List<SysPermissionAll> all = new ArrayList<>();
        for (SysPermissionAll sysPermissionAll : tempAll) {
            if (StringUtils.isEmpty(sysPermissionAll.getParentId())) {
                sysPermissionAll.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", sysPermissionAll.getUpdateTime()));
                sysPermissionAll.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), sysPermissionAll.getPermissionTypeValue()));

                List<SysPermissionAll> children = getChildren(sysPermissionAll.getId(), tempAll);
                if (CollectionUtils.isNotEmpty(children)) {
                    sysPermissionAll.setChildren(children);
                    sysPermissionAll.setDel(false);
                } else {
                    sysPermissionAll.setDel(true);
                }
                all.add(sysPermissionAll);

                if (sysPermissionAll.getIsH5()) {
                    sysPermissionAll.setIsH5Str("1");
                } else {
                    sysPermissionAll.setIsH5Str("0");
                }
            }
        }
        return all;
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateData(SysPermissionAll sysPermissionAll) {
        String userId = RequestHeaderUtils.getUserId(request);
        // 校验必填
        if (StringUtils.isEmpty(sysPermissionAll.getSystemCode()) || StringUtils.isEmpty(sysPermissionAll.getPermissionCode()) || StringUtils.isEmpty(sysPermissionAll.getPermissionName())
                || StringUtils.isEmpty(sysPermissionAll.getPermissionTypeValue()) || StringUtils.isEmpty(sysPermissionAll.getIsFrame()) || StringUtils.isEmpty(sysPermissionAll.getPath())
                || StringUtils.isEmpty(sysPermissionAll.getActiveRule()) || StringUtils.isEmpty(sysPermissionAll.getOpenType()) || null == sysPermissionAll.getSort()) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        if ("0".equals(sysPermissionAll.getIsH5Str())) {
            sysPermissionAll.setIsH5(false);
        } else {
            sysPermissionAll.setIsH5(true);
        }
        sysPermissionAll.setPermissionTypeKey(ConfigDictTypeEnum.MENUTYPE.getCode());
        // 校验编码不能重复
        LambdaQueryWrapper<SysPermissionAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermissionAll::getDisabled, 0);
        queryWrapper.eq(SysPermissionAll::getPermissionCode, sysPermissionAll.getPermissionCode());
        if (StringUtils.isNotEmpty(sysPermissionAll.getId())) {
            queryWrapper.ne(SysPermissionAll::getId, sysPermissionAll.getId());
        }
        List<SysPermissionAll> sysPermissionAlls = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(sysPermissionAlls)) {
            return new ResultBean<>().build("菜单编码已存在，请重新填写！");
        }
        if (StringUtils.isEmpty(sysPermissionAll.getId())) {
            sysPermissionAll.setCreaterId(userId);
            sysPermissionAll.setUpdateId(userId);
            baseMapper.insert(sysPermissionAll);
        } else {
            SysPermissionAll updateInfo = baseMapper.selectById(sysPermissionAll.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysPermissionAll, updateInfo);
            updateInfo.setUpdateId(userId);
            updateInfo.setUpdateTime(new Date());
            baseMapper.updateById(updateInfo);
        }
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public SysPermissionAll getDetail(String id) {
        SysPermissionAll sysPermissionAll = baseMapper.selectById(id);
        sysPermissionAll.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), sysPermissionAll.getPermissionTypeValue()));
        if (sysPermissionAll.getIsH5()) {
            sysPermissionAll.setIsH5Str("1");
        } else {
            sysPermissionAll.setIsH5Str("0");
        }
        return sysPermissionAll;
    }

    @Override
    public ResultBean<JSONObject> deleteData(String id) {
        // 判断是否已被项目引用，已引用不可删除；
        SysPermissionAll sysPermissionAll = baseMapper.selectById(id);
        SysTenantPermission sysTenantPermission = sysTenantPermissionService.selectExist(sysPermissionAll.getPermissionCode());
        if (null != sysTenantPermission) {
            return new ResultBean<>().build("该菜单已被引用，无法删除！");
        }

        sysPermissionAll.setDisabled(1);
        String userId = RequestHeaderUtils.getUserId(request);
        sysPermissionAll.setUpdateId(userId);
        sysPermissionAll.setUpdateTime(new Date());
        baseMapper.updateById(sysPermissionAll);

        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public SysPermissionAll getByMenuCode(String permissionCode) {
        LambdaQueryWrapper<SysPermissionAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermissionAll::getDisabled, 0);
        queryWrapper.eq(SysPermissionAll::getPermissionCode, permissionCode);
        queryWrapper.last(" limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

    private List<SysPermissionAll> getChildren(String parentId, List<SysPermissionAll> tempAll) {
        List<SysPermissionAll> ret = new ArrayList<>();
        for (SysPermissionAll child : tempAll) {
            if (StringUtils.isNotEmpty(child.getParentId()) && parentId.equals(child.getParentId())) {
                child.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), child.getPermissionTypeValue()));
                child.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", child.getUpdateTime()));
                List<SysPermissionAll> children = getChildren(child.getId(), tempAll);
                if (CollectionUtils.isNotEmpty(children)) {
                    child.setChildren(children);
                    child.setDel(false);
                } else {
                    child.setDel(true);
                }
                ret.add(child);
            }
        }
        return ret;
    }
}
